package com.attendance.config;

import com.attendance.entity.User;
import com.attendance.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;


@Component
public class DBUserDetailsManager implements UserDetailsManager, UserDetailsService {

    @Resource
    private UserServiceImpl service;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = service.searchInfoByEmail(email);
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(() -> "USER_ISAUTHENTICATION");
        // 权限载入
        if (user == null) {
            throw new UsernameNotFoundException(email);
        } else {
            return org.springframework.security.core.userdetails.User
                    .withUsername(email)
                    .password(user.getPassword())
                    .accountExpired(!user.getAccountNonExpired())
                    .accountLocked(!user.getAccountNonLocked())
                    .credentialsExpired(!user.getCredentialsNonExpired())
                    .disabled(!user.getEnabled())
                    .authorities(authorities).build();
        }
    }

    @Override
    public void createUser(UserDetails user) {

    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }
}

